<?php
/**
 * Created by PhpStorm.
 * User: BesonTD
 * Date: 15-3-18
 * Time: 上午10:58
 */
defined('BYshopJL') or exit('Access Invalid!');

class weixin
{
    public static $WEIXIN_APP_ID = "wxf232edb6ee8c5e81";//公众号的唯一标识
    public static $SECRET = "191fb5fba463aaebf360ae439bc46ef2";//公众号的appsecret
    private $sns_userinfo = "snsapi_userinfo";//授权方式
    private $sns_base = "snsapi_base";//授权方式
    public $code;//网页授权 code
    private $authorised;//授权方式

    public function __construct($authorised = 1)
    {
        $this->authorised = $authorised == 2 ? $this->sns_userinfo : $this->sns_base;

        if (isset($_GET['code']) && !empty($_GET['code'])) $this->code = $_GET['code'];
    }

    /**
     * webAuthGetCode
     * 微信网页授权第一步 ，获取code
     */
    public function webAuthGetCode()
    {
        $requestUrl = "http://6.080c.com/{$_SERVER['REQUEST_URI']}";//SITE_URL . $_SERVER['REQUEST_URI'];
        $oauthUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . self::$WEIXIN_APP_ID . '&redirect_uri=' . urlencode($requestUrl) . '&response_type=code&scope=' . $this->authorised . '&state=oauth#wechat_redirect';
        header('Location:' . $oauthUrl);
        exit;
    }

    /**
     * webAuthGetAccessToken
     * 微信网页授权第二步，获取access_token
     * @return bool|mixed
     */
    public function webAuthGetAccessToken()
    {
        if (empty($this->code)) {
            return false;
        }
        $requestUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . self::$WEIXIN_APP_ID . '&secret=' . self::$SECRET . '&code='.$this->code.'&grant_type=authorization_code';
        $result = json_decode(self::curlGet($requestUrl),true);
        return $result;
    }

    /**
     * webAuthTokenStatus
     * 查看网页授权access_token 过期状态
     * @param $token
     * @param $opinid
     * @return bool
     */
    public function webAuthTokenStatus($token, $openid)
    {
        $valid_url = 'https://api.weixin.qq.com/sns/auth?access_token=' . $token . '&openid=' . $openid;
        $valid_result = json_decode(self::curlGet($valid_url));
        //过期状态
        if ($valid_result['errcode'] == 0) return true;
        return false;
    }

    /**
     * webAuthRefreshToken
     * 网页授权刷新 access_token
     * @param $refresh_token
     * @return mixed
     */
    public function webAuthRefreshToken($refresh_token)
    {
        $requestUrl = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . self::$WEIXIN_APP_ID . '&grant_type=refresh_token&refresh_token=' . $refresh_token;
        $result = json_decode(self::curlGet($requestUrl));
        return $result;
    }

    /**
     * getUserInfo
     * 网页授权最后一步，获取用户信息
     * @param $token
     * @param $openid
     * @param $refresh_token
     * @return mixed
     */
    public function getUserInfo($token, $openid, $refresh_token)
    {
        //查看$token 状态
        $token_status = $this->webAuthTokenStatus($token, $openid);
        if (!$token_status) {
            //刷新access_token
            $result = $this->webAuthRefreshToken($refresh_token);
            $openid = $result['openid'];
            $token = $result['access_token'];
        }
        $requestUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $token . '&openid=' . $openid . '&lang=zh_CN';
        $result = json_decode(self::curlGet($requestUrl));
        return $result;
    }


    private function curlGet($url, $data = '')
    {
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        return $temp;
    }

} 